package com.yxjx.duoxue;

import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.Executors;

import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import com.baidu.lbsapi.auth.LBSAuthManagerListener;
import com.baidu.location.LocationClient;
import com.baidu.navisdk.BaiduNaviManager;
import com.baidu.navisdk.BNaviEngineManager.NaviEngineInitListener;
import com.tencent.android.tpush.XGPushConfig;
import com.tencent.android.tpush.XGPushManager;
import com.tencent.stat.StatConfig;
import com.tencent.stat.StatService;
import com.umeng.analytics.MobclickAgent;
import com.yxjx.duoxue.course.SearchCondition;
import com.yxjx.duoxue.database.YxDataBase;
import com.yxjx.duoxue.datamodel.DMAdItem;
import com.yxjx.duoxue.datamodel.DMArea;
import com.yxjx.duoxue.datamodel.DMBaiduLocation;
import com.yxjx.duoxue.datamodel.DMCallRecord;
import com.yxjx.duoxue.datamodel.DMCourseCategory;
import com.yxjx.duoxue.datamodel.DMKeyword;
import com.yxjx.duoxue.datamodel.DMOpenApp;
import com.yxjx.duoxue.datamodel.course.DMCourse;
import com.yxjx.duoxue.global.Globals;
import com.yxjx.duoxue.network.NwUtils;
import com.yxjx.duoxue.network.URMobileCheckResponse;
import com.yxjx.duoxue.network.UserLoginResponse;
import com.yxjx.duoxue.network.UserReg;
import com.yxjx.duoxue.user.UserLogin;
import com.yxjx.duoxue.utils.UIHelper;
import com.yxjx.duoxue.utils.Utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;


public class AppLoadingActivity extends BaseNoActionBarActivity {
	
	private boolean mCourseCategoryReady;
	private boolean mAreaInfoReady;
	private boolean mAdReady;
	private ArrayList<DMAdItem> mAds = null;
	private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        Bundle extra = getIntent().getExtras();
        Log.d("CMM1", "start loading activity, extra = " + extra);
        if (extra != null) {
        	Log.d("CMM1", "extra = " + extra.getString("key_course_id"));
        }
        mRoot = findViewById(R.id.root);
        
        // Nav init
     // 初始化导航引擎
//		BaiduNaviManager.getInstance().initEngine(this, getSdcardDir(),
//				mNaviEngineInitListener, "hqheGXCH8raBkNNYhmqmYn5q", null);
        BaiduNaviManager.getInstance().initEngine(this, getSdcardDir(),
                mNaviEngineInitListener, new LBSAuthManagerListener() {
                    @Override
                    public void onAuthResult(int status, String msg) {
                        String str = null;
//                        if (0 == status) {
//                            str = "key校验成功!";
//                        } else {
//                            str = "key校验失败, " + msg;
//                        }
//                        Toast.makeText(AppLoadingActivity.this, str,
//                                Toast.LENGTH_LONG).show();
                    }
                });
    }

	private void loading() {
        // MTA enable
        // for mta
        StatConfig.setDebugEnable(true);
        StatConfig.setAutoExceptionCaught(true);
        StatService.trackCustomEvent(this, "onCreate", "");
       
        
        // if Network is not ready, then Toast it.
        if (Utils.getNetworkInfo(getApplicationContext()) == Utils.NW_TYPE_NO_CONN) {
        	Toast.makeText(getApplicationContext(), "无法连接到网络,请检查网络设置", Toast.LENGTH_SHORT).show();
        }
        
		// 尝试打开地图
        LocationClient client = Globals.getInstance(this).getLocationClient();
        if (client != null) {
        	if (!client.isStarted()) {
        		client.start();
        		client.getLocOption().setOpenGps(true);
        	}
        }
        
        // init for async loading images from web.
        UIHelper.init();
        
        // loading necessary and then start home page.
//        LoadingAsyncTask courseReady = new LoadingAsyncTask();
////        courseReady.execute("");
//        courseReady.executeOnExecutor(Executors.newCachedThreadPool(), "");
        
        Thread start = new Thread(new Runnable() {
			
			@Override
			public void run() {
				
				if (UserLogin.tryUserLogin(mContext)
						&& PageLoading.getCurrentLocation(AppLoadingActivity.this)) {
					mHandler.sendEmptyMessage(Yx.MSG_LOAD_DONE);
				}
			}
		});
        start.setPriority(Thread.MAX_PRIORITY);
        start.start();
        
        // 记录打开APP的信息,将记录写到数据库。
		DMOpenApp openAppRecord = DMOpenApp.getNewRecord(AppLoadingActivity.this);
		YxDataBase.getInstance(AppLoadingActivity.this).insertOpenAppRecord(openAppRecord);
		// 纪录APP打开的次数
		Utils.addAppOpenTime(this);
	
	}
    
	private Handler mHandler = new Handler() {
    	@Override
    	public void handleMessage(android.os.Message msg) {
    		switch (msg.what) {
			case Yx.MSG_LOAD_DONE:
				removeMessages(Yx.MSG_LOAD_DONE);
				startHomePage();
				break;
			default:
				break;
			}
    		
    	}
    };
	private View mRoot;
    
 
    


    
    private void startHomePage() {
    	String hasFirstBootup = Utils.getValueFromSharedPreference(this, Yx.KEY_FIRST_BOOTUP);
    	Intent intent = new Intent();
    	if (UIHelper.isEmpty(hasFirstBootup) || !hasFirstBootup.equals("1")) {
    		Utils.writeToSharePreference(this, Yx.KEY_FIRST_BOOTUP, "1");
    		// TODO: some phone may have many shortcuts, will fix it in the future;
    		createDeskShortCut();
        	intent.setClass(getApplicationContext(), GuidingActivity.class);
    	} else {
        	intent.setClass(getApplicationContext(), HomePageActivity.class);
    	}
    	// 将通知得到的extra塞到intent中
    	String extraPushCustom = getIntent().getStringExtra(Yx.KEY_PUSH_EXTRA_CUSTOM);
		intent.putExtra(Yx.KEY_PUSH_EXTRA_CUSTOM, extraPushCustom);
    	startActivity(intent);
    	Utils.logd("CMM8, startHomePage() intent.cmp = " + intent.getComponent());
    	finish();
    }
    
    @Override
    protected void onResume() {
    	MobclickAgent.onResume(this);
    	super.onResume();
    	mRoot.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				loading();
			}
		}, 500);
    }
    
    @Override
    protected void onPause() {
    	MobclickAgent.onPause(this);
    	super.onPause();
    }
    
    //////////
	/**
	 * 创建快捷方式
	 */
	public void createDeskShortCut() {
		Log.i("coder", "------createShortCut--------");
		// 创建快捷方式的Intent
		Intent shortcutIntent = new Intent(
				"com.android.launcher.action.INSTALL_SHORTCUT");
		// 不允许重复创建
		shortcutIntent.putExtra("duplicate", false);
		// 需要现实的名称
		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
				getString(R.string.app_name));

		// 快捷图片
		Parcelable icon = Intent.ShortcutIconResource.fromContext(
				getApplicationContext(), R.drawable.logo);

		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);

		Intent intent = new Intent(getApplicationContext(),
				AppLoadingActivity.class);
		// 下面两个属性是为了当应用程序卸载时桌面 上的快捷方式会删除
		intent.setAction("android.intent.action.MAIN");
		intent.addCategory("android.intent.category.LAUNCHER");
		// 点击快捷图片，运行的程序主入口
		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
		// 发送广播。OK
		sendBroadcast(shortcutIntent);
	}
    
	
	// Nav init
	private boolean mIsEngineInitSuccess = false;
	private NaviEngineInitListener mNaviEngineInitListener = new NaviEngineInitListener() {
		public void engineInitSuccess() {
			// 导航初始化是异步的，需要一小段时间，以这个标志来识别引擎是否初始化成功，为true时候才能发起导航
			mIsEngineInitSuccess = true;
		}

		public void engineInitStart() {
		}

		public void engineInitFail() {
		}
	};

	private String getSdcardDir() {
		if (Environment.getExternalStorageState().equalsIgnoreCase(
				Environment.MEDIA_MOUNTED)) {
			return Environment.getExternalStorageDirectory().toString();
		}
		return null;
	}

}
